import time
from datetime import datetime
import requests
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from tools.log import logger

def create_session_with_retries():
    session = requests.Session()
    retries = Retry(
        total=3,
        backoff_factor=1,
        status_forcelist=[500, 502, 503, 504]
    )
    session.mount('http://', HTTPAdapter(max_retries=retries))
    # session.mount('https://', HTTPAdapter(max_retries=retries))
    return session

def send_json_request(url, payload, headers=None):
    try:
        with create_session_with_retries() as session:
            response = session.post(
                url,
                json=payload,
                headers=headers or {},
                timeout=(3.05, 27)  # 连接超时和读取超时
            )
            response.raise_for_status()
        return {
            "success": True
        }
    except requests.exceptions.HTTPError as http_err:
        return {
            "success": False,
            "error": f"HTTP错误: {http_err}",
            "status_code": http_err.response.status_code if hasattr(http_err, 'response') else None
        }
    except Exception as err:
        return {
            "success": False,
            "error": f"请求错误: {err}"
        }


def work(global_conf, camera_conf):
   interval = global_conf["alive"]["interval"]
   data_format = {
      "position":camera_conf["position"],
      "boxId":global_conf["box"]["id"],
      "updateTime": datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
      "cameraId":camera_conf["id"],
      "userName":global_conf["box"]["user"]
   }

   while True:
        res = send_json_request(
                url=global_conf["alive"]["api"],
                payload=data_format
            )
        if res["success"]:
            logger.info(f"INFO:: { camera_conf['id']} 状态更新成功! {time.time()}")
        else:
            logger.warning(f"WARN:: { camera_conf['id']} 状态更新失败! {time.time()}")
        time.sleep(interval)
   